package com.jaydenxiao.common.commonutils;

import android.text.TextUtils;
import android.util.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Base64Utils {
    /**
     * encodeBase64File:(将文件转成base64 字符串). <br/>
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     * @since JDK 1.6
     */
    public static String encodeBase64File(String path, String encry) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        String encode = "";
        if (TextUtils.isEmpty(encry)) {
            encode = "";
        } else {
            encode = com.jaydenxiao.common.security.Base64.encode(encry.getBytes());
        }
        inputFile.read(buffer);
        inputFile.close();
        return encode + Base64.encodeToString(buffer, Base64.DEFAULT);
    }


    /**
     * decoderBase64File:(将base64字符解码保存文件). <br/>
     *
     * @param base64Code 编码后的字串
     * @param savePath   文件保存路径
     * @throws Exception
     * @since JDK 1.6
     */
    public static void decoderBase64File(String base64Code, String savePath, String name) throws Exception {
        File dir = new File(savePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File f = new File(savePath, name);
        if (!f.exists()) {
            f.createNewFile();
        } else {
            f.delete();
        }
        byte[] buffer = Base64.decode(base64Code, Base64.DEFAULT);
        FileOutputStream out = new FileOutputStream(f);
        out.write(buffer);
        out.close();
    }

    /**
     * decoderBase64File:(将base64字符解码保存文件). <br/>
     *
     * @param base64Code 编码后的字串
     * @param savePath   文件保存路径
     * @throws Exception
     * @since JDK 1.6
     */
    public static File decoderBase64Filedata(String base64Code, String savePath, String name) throws Exception {
        File dir = new File(savePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File f = new File(savePath, name);
        if (!f.exists()) {
            f.createNewFile();
        } else {
            f.delete();
        }
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(f);
        out.write(buffer);
        out.close();
        return f;
    }
}